package io.nutz.nutzsite.module.sys.controllers;

import io.nutz.nutzsite.common.base.Result;
import io.nutz.nutzsite.common.socket.WkNotifyService;
import io.nutz.nutzsite.module.sys.models.MsgUser;
import io.nutz.nutzsite.module.sys.models.User;
import io.nutz.nutzsite.module.sys.services.MsgUserService;
import io.nutz.nutzsite.module.sys.services.UserService;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.session.Session;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.nutz.dao.Cnd;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.Lang;
import org.nutz.lang.Strings;
import org.nutz.lang.util.NutMap;
import org.nutz.log.Log;
import org.nutz.log.Logs;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.Ok;
import org.nutz.mvc.annotation.POST;
import org.nutz.mvc.annotation.Param;
import org.nutz.plugins.slog.annotation.Slog;
/**
 * 推送消息用户 信息操作处理
 * 
 * @author lrw
 * @date 2020-03-27
 */
@IocBean
@At("/sys/msgUser")
public class MsgUserController {
	private static final Log log = Logs.get();
	@Inject
    private UserService userService;
	@Inject
	private WkNotifyService wkNotifyService;
	@Inject
	private MsgUserService msgUserService;
	@Inject("refer:shiroWebSessionManager")
    private DefaultWebSessionManager webSessionManager;
	
	
	@RequiresPermissions("sys:msgUser:view")
	@At("")
	@Ok("th:/sys/msgUser/msgUser.html")
	public void index(HttpServletRequest req) {

	}

	/**
	 * 查询推送消息用户列表
	 */
	@RequiresPermissions("sys:msgUser:list")
	@At
	@Ok("json")
	public Object list(@Param("pageNum")int pageNum,
					   @Param("pageSize")int pageSize,
					   @Param("name") String name,
					   @Param("beginTime") Date beginTime,
					   @Param("endTime") Date endTime,
					   @Param("orderByColumn") String orderByColumn,
					   @Param("isAsc") String isAsc,
					   HttpServletRequest req) {
		Cnd cnd = Cnd.NEW();
		if (!Strings.isBlank(name)){
			//cnd.and("name", "like", "%" + name +"%");
		}
		if(Lang.isNotEmpty(beginTime)){
			cnd.and("create_time",">=", beginTime);
		}
		if(Lang.isNotEmpty(endTime)){
			cnd.and("create_time","<=", endTime);
		}
		return msgUserService.tableList(pageNum,pageSize,cnd,orderByColumn,isAsc,null);
	}

	/**
	 * 新增推送消息用户
	 */
	@At("/add")
	@Ok("th:/sys/msgUser/add.html")
	public void add( HttpServletRequest req) {

	}
	/**
	 * 主动推送消息到客户端ws
	 * 如果提供房间号，则推送给同房间的所有人
	 * 用户id——user表中sessionid——webSessionManager找出Session——取出wsid
	 * @param msg
	 * @param room
	 * @param req
	 * @return
	 */
	@At("/sendmsg")
	@Ok("json")
	public Object sendmsg(@Param("ids") String ids, @Param("msg") String msg, 
			HttpServletRequest req,HttpSession ses) {
		List<String> wsids=new ArrayList<String>();
		NutMap map=new NutMap();
		if(ids!="home"){
			List<User> users = userService.query(Cnd.where("id", "in", ids.split(",")));
			for( User u:users ){
				String ssid=u.getSessionId();
				try{
					Session oldSession = webSessionManager.getSessionDAO().readSession(ssid);
					String wsid=(String)oldSession.getAttribute("wsid");
					wsids.add(wsid);
				}catch(Exception ex){
					//log.debug("\r\n no wsid:"+ex.getMessage());
					//return Result.error(ex.getMessage());
				}
			}
		}
		else wsids.add("home");
		map.addv("action", "notify");
		map.put("title", "您有新的消息");
        map.put("body", msg);
        map.put("url", "");
		wkNotifyService.sayhi(wsids,map);
		return Result.success("system.success");
	}
	/**
	 * 新增保存推送消息用户
	 */
	@At
	@POST
	@Ok("json")
	@RequiresPermissions("sys:msgUser:add")
	@Slog(tag="推送消息用户", after="新增保存推送消息用户 id=${args[0].id}")
	public Object addDo(@Param("..") MsgUser msgUser,HttpServletRequest req) {
		try {
			msgUserService.insert(msgUser);
			return Result.success("system.success");
		} catch (Exception e) {
			return Result.error("system.error");
		}
	}

	/**
	 * 修改推送消息用户
	 */
	@At("/edit/?")
	@Ok("th://sys/msgUser/edit.html")
	public void edit(String id, HttpServletRequest req) {
		MsgUser msgUser = msgUserService.fetch(id);
		req.setAttribute("msgUser",msgUser);
	}

	/**
	 * 修改保存推送消息用户
	 */
	@At
	@POST
	@Ok("json")
	@RequiresPermissions("sys:msgUser:edit")
	@Slog(tag="推送消息用户", after="修改保存推送消息用户")
	public Object editDo(@Param("..") MsgUser msgUser,HttpServletRequest req) {
		try {
			if(Lang.isNotEmpty(msgUser)){
				//msgUser.setUpdateBy(ShiroUtils.getSysUserId());
				//msgUser.setUpdateTime(new Date());
				msgUserService.update(msgUser);
			}
			return Result.success("system.success");
		} catch (Exception e) {
			return Result.error("system.error");
		}
	}

	/**
	 * 删除推送消息用户
	 */
	@At("/remove")
	@Ok("json")
	@RequiresPermissions("sys:msgUser:remove")
	@Slog(tag ="推送消息用户", after= "删除推送消息用户:${array2str(args[0])}")
	public Object remove(@Param("ids")String[] ids, HttpServletRequest req) {
		try {
			msgUserService.delete(ids);
			return Result.success("system.success");
		} catch (Exception e) {
			return Result.error("system.error");
		}
	}

}
